import {
  EditorButton,
  EditorSettings,
  PersistenMode,
  PersistentSettings,
  Status,
  useSettingsStore,
} from '@/store';

function isScopePersistent(persistentSettings: PersistentSettings) {
  return (
    persistentSettings.needPersistent &&
    (persistentSettings.currentMode === PersistenMode.FlickerFreeMode ||
      persistentSettings.currentMode === PersistenMode.RollPollingMode)
  );
}

// 进入编辑模式
function enterEditor(event: MouseEvent, persistentSettings: PersistentSettings) {
  const target = event.target as HTMLElement;
  if (target) {
    // 如果是局部持久化模式,当点击的元素具有子元素,直接退出,不然会导致修改信息时删除子元素而改变了节点结构
    if (isScopePersistent(persistentSettings) && target.children.length > 0) {
      return;
    }
    target.contentEditable = 'true';
    target.focus();
  }
}

function checkKey(event: MouseEvent, editorSettings: EditorSettings): boolean {
  if (
    event.ctrlKey === editorSettings.ctrl &&
    event.altKey === editorSettings.alt &&
    event.shiftKey === editorSettings.shift
  ) {
    return true;
  }
  return false;
}

export function useEditor() {
  const editorSettings = useSettingsStore((state) => state.editorSettings);
  const persistentSettings = useSettingsStore((state) => state.persistentSettings);
  const status = useSettingsStore((state) => state.status);

  useEffect(() => {
    if (status === Status.STOP) {
      return;
    }
    function handerContextmenu(event: MouseEvent) {
      if (checkKey(event, editorSettings)) {
        event.preventDefault();
        event.stopPropagation();
        enterEditor(event, persistentSettings);
      }
    }

    function handerClick(event: MouseEvent) {
      if (checkKey(event, editorSettings)) {
        event.preventDefault();
        event.stopPropagation();
        enterEditor(event, persistentSettings);
      }
    }
    if (editorSettings.button === EditorButton.RIGHT) {
      window.addEventListener('contextmenu', handerContextmenu, {
        capture: true,
      });
    }
    if (editorSettings.button === EditorButton.LEFT) {
      window.addEventListener('click', handerClick, {
        capture: true,
      });
    }
    return () => {
      window.removeEventListener('contextmenu', handerContextmenu, {
        capture: true,
      });
      window.removeEventListener('click', handerClick, {
        capture: true,
      });
    };
  }, [editorSettings, status, persistentSettings]);
}
